//车辆管理
/**
 * fixed by zhaojian
 */
interface ICarManagentViewModel extends IBaseViewModel<ICarManagentQueryTerms> {
    /**
     * ui-grid控制
     */
    gridOptions: uiGrid.IGridOptionsOf<CarListItemResponse>;
    /**
     * 车长下拉
     */
    carLengthDropDown: ValueListItemResponse[];
    /**
     * 车型下拉
     */
    carTypeDropDown: ValueListItemResponse[];
    /**
     * 承运类别下拉
     */
    carrierCategoryDropDown: ValueListItemResponse[];
    /**
     * LBS定位
     */
    carLbs: (id: string, carCode: string, phone: string) => void;
    /**
     * 禁用或启用车辆
     */
    disabledOrEnabledCar: (id: string, isEnabled: boolean) => void;
    /**
     * 删除车辆
     */
    deleteCar: (id: string) => void;
    /**
     * 翻页后选中
     */
    resumeSelectedItem:()=>void;
    /**
     * 列表高
     */
    heightA:number;
       
}
interface CarListData {
    /**
     * id
     */
    id:string;
    /**
     * 启用、禁用
     */
    isenabled:boolean

}

interface ICarManagentQueryTerms {
    /**
     * 车牌号
     */
    carCode: string;
    /**
     * 车型
     */
    carType: string;
    /**
     * 车长
     */
    carLength: string;
    /**
     * 录入人
     */
    inputPerson: string;
    /**
     * 驾驶员
     */
    driver: string;
    /**
     * 驾驶员号码
     */
    driverPhone: string;
    /**
     * 承运类被
     */
    carrierCategory: string;
    /**
     * 主营线路
     */
    mainRoute: string;
    /**
     * 是否启用
     */
    isEnabled: boolean;
    /**
     * 开始时间
     */
    startTime: string;
    /**
     * 结束时间
     */
    endTime: string;
}

class carManagentController extends ListController<ICarManagentViewModel, ICarManagentQueryTerms> {
    gridApi: uiGrid.IGridApiOf<CarListItemResponse>;
    /**
     * 保已选车辆，在重新查询后会清除
     */
    selectedCarIds: CarListData[];
    /**
     * 选定选中，防止在翻页恢复选中效果时候误操作
     */
    lockSelect: boolean = false;
    orderBy: number = 0;
    asc: boolean = true;
    /**
     * 列表数据
     */
    carDataList:Array<CarListItemResponse>;

    skip:number=0;

    constructor($scope: ICarManagentViewModel, private carService: ICarService, private valueService: IValueService, private $ngBootbox: BootboxService, private $state: angular.ui.IStateService,private $timeout:ng.ITimeoutService,
    private exportService:IexportService,private $location:ng.ILocationService) {
        super($scope);
        this.init();
    }

    init(): void {
        super.init();

        this.$scope.carLbs = this.carLbs;
        // this.$scope.disabledOrEnabledCar = this.disabledOrEnabledCar;
        this.$scope.deleteCar = this.deleteCar;
        // this.$scope.batchDisabledCar = this.batchDisabledCar;
        // this.$scope.batchEnabledCar = this.batchEnabledCar;

        this.$scope.queryTerms = {
            carCode: "",
            carType: "",
            carLength: "",
            inputPerson: "",
            driver: "",
            driverPhone: "",
            carrierCategory: "",
            mainRoute: "",
            isEnabled: null,
            startTime: "",
            endTime: ""
        };

        this.$scope.gridOptions = {
            paginationPageSizes: [10, 20, 30],
            useExternalPagination: true,
            useExternalSorting: true,
            enableFullRowSelection: true,
            enableColumnResizing: true,
            columnDefs: [
                { displayName: "车牌号", field: 'carCode', enableColumnMenu: false, cellTooltip: true, headerTooltip: true },
                { displayName: "车型", field: 'carType', enableColumnMenu: false, cellTooltip: true, headerTooltip: true },
                { displayName: '车长', field: 'carLength', enableColumnMenu: false, cellTooltip: true, headerTooltip: true },
                { displayName: '主营路线', field: 'mainRoute', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '10%' },
                { displayName: '驾驶员姓名', field: 'driver', enableColumnMenu: false, cellTooltip: true, headerTooltip: true },
                { displayName: '驾驶员号码', field: 'driverPhone', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '10%' },
                { displayName: '承运类别', field: 'carrierCategory', enableColumnMenu: false, cellTooltip: true, headerTooltip: true },
                { displayName: '录入人', field: 'inputPerson', enableColumnMenu: false, cellTooltip: true, headerTooltip: true },
                { displayName: '录入时间', field: 'creationTime', enableColumnMenu: false, cellTooltip: true, headerTooltip: true },
                { displayName: '定位状态', field: 'isCanTargeted', cellTemplate: '<span ng-if="row.entity.isCanTargeted">已开通</span><span ng-if="!row.entity.isCanTargeted">未开通</span>', enableColumnMenu: false, cellTooltip: true, headerTooltip: true },
                {
                    displayName: "操作",
                    field: '操作',
                    cellFilter: 'checkmark',
                    cellTemplate: '<a  class="fa fa-eye m-l-xs primary text-info" title="查看" ui-sref="app.car.carManagent_edit({id:row.entity.id,name:\'carManagentDetail\'})"></a>&nbsp;&nbsp;<a class="primary fa fa-location-arrow text-primary" title="定位跟踪" ng-click="grid.appScope.carLbs(row.entity.id,row.entity.carCode,row.entity.driverPhone)"></a>',
                    enableColumnMenu: false,
                    enableSorting: false
                }
            ],
            onRegisterApi: (gridApi) => {
                this.gridApi = gridApi;
                gridApi.pagination.on.paginationChanged(this.$scope,(skipSize,pageSize)=>{
                    this.paginationChanged(skipSize,pageSize,this.$state);
                });
                // gridApi.pagination.on.paginationChanged(this.$scope, this.paginationChanged);
                gridApi.core.notifyDataChange("options");
                gridApi.core.on.sortChanged(this.$scope, this.sortChange);
                // gridApi.selection.on.rowSelectionChanged(this.$scope, this.selectChange);
                // gridApi.selection.on.rowSelectionChangedBatch(this.$scope, this.batchSelectChange);
            }
        }

        this.query();     
        this.loadCarLengthDropDown();
        this.loadCarTypeDropDown();
        this.loadCarrierCategoryDropDown();

        $('#openstartTime').click(function () {
            $('#startTime').datetimepicker('show');
        });

        $('#openendTime').click(function () {
            $('#endTime').datetimepicker('show');
        });
    }

    loadData(queryTerms: ICarManagentQueryTerms, skip: number, count: number): void {
        this.carService.getList(this.orderBy, this.asc, queryTerms.carCode, queryTerms.carType, queryTerms.carLength,
            queryTerms.inputPerson, queryTerms.driver, queryTerms.driverPhone, queryTerms.carrierCategory, queryTerms.mainRoute,
            queryTerms.isEnabled,queryTerms.startTime, queryTerms.endTime, skip, count).then(result => {
                this.$scope.gridOptions.totalItems = result.data.total;
                this.$scope.gridOptions.data = result.data.data;
                this.$scope.heightA = ((this.$scope.gridOptions.data.length * 39) + 95);

                if (skip == 0) {
                    this.$scope.gridOptions.paginationCurrentPage = 1;
                }
                this.skip = skip;

                this.resumeSelectedItem(this.$scope.gridOptions.data);
                this.$scope.querying = false;
            }, error => {
                this.$scope.querying = false;
            });
    }

    localHistory():void{
        super.localHistory(this.$state);
    }
    getHistory():void{
        super.getHistory(this.$state,this.$location)
    }
   
    onQuery():void {
        super.onQuery();
        this.selectedCarIds = [];
    }

    loadCarLengthDropDown(): void {
        this.$scope.carLengthDropDown = this.valueService.getCarLengthList().data;
    }

    loadCarTypeDropDown(): void {
        this.$scope.carTypeDropDown = this.valueService.getCarTypeList().data;
    }

    loadCarrierCategoryDropDown(): void {
        this.$scope.carrierCategoryDropDown = this.valueService.getCarriageTypeList().data;
    }

    /**
     * 排序事件触发
     */
    sortChange=(grid: uiGrid.IGridInstanceOf<CarListItemResponse>, sortColumns: Array<uiGrid.IGridColumnOf<CarListItemResponse>>)=> {
        if (sortColumns.length == 0) {
            this.reload();
        } else {
            let sortItem = sortColumns[0];
            switch (sortItem.name) {
                case "carCode": {
                    this.orderBy = 1;
                } break;
                case "carType": {
                    this.orderBy = 3;
                } break;
                case "carLength": {
                    this.orderBy = 4;
                } break;
                case "inputPerson": {
                    this.orderBy = 5;
                } break;
                case "driver": {
                    this.orderBy = 6;
                } break;
                case "driverPhone": {
                    this.orderBy = 7;
                } break;
                case "carrierCategory": {
                    this.orderBy = 8
                } break;
                case "mainRoute": {
                    this.orderBy = 9;
                } break;
                case "location": {
                    this.orderBy = 10;
                } break;
                case "locationDateTime": {
                    this.orderBy = 11;
                } break;
            }
            this.asc = sortItem.sort.direction == "asc";
            this.reload();
        }
    }

    /**
     * 删除车辆
     */
    deleteCar = (id: string) => {
        this.$ngBootbox.confirm("确定删除该数据？").then(e => {
            this.carService.delete(id).then(result => {
                this.reload();
            });
        });
    }

    /**
     * 打开LBS定位界面
     */
    carLbs = (id: string, carCode: string, phone: string) => {
        this.$state.go("app.car.carLocation", { id: id, carcode: carCode, phone: phone });
    }

    /**
     * 恢复选中
     */
    resumeSelectedItem(data : string | CarListItemResponse[]):void {
        if (this.selectedCarIds.length <= 0) {
            return;
        }
        if (this.isCarListItemResponse(data)) {
            data.forEach((item, index) => {
                this.selectedCarIds.forEach((itemS,indexS)=>{
                    if (item.id===itemS.id) {
                        //this.lockSelect = true;
                        this.$timeout(()=>{
                            if (this.isCarListItemResponse(data)){
                                this.lockSelect = true;
                                this.gridApi.selection.selectRow(data[index]);
                                console.log(this.selectedCarIds)
                                this.lockSelect = false;
                            }
                        });
                    }
                });
            });
        }
    }

    //断言
    isCarListItemResponse(response: string | CarListItemResponse[]): response is CarListItemResponse[] {
        return (<CarListItemResponse[]>response).forEach !== undefined;
    }


    /**
     * 导出列表
     */
    exportFunc=()=>{
        if(this.$scope.gridOptions.totalItems>60000){
            this.$ngBootbox.alert('导出数据不可超过6万条');
            return;
        }else{
            this.exportService.exportCar(this.orderBy.toString(),this.asc,this.queryTerms.carCode,this.queryTerms.carType,this.queryTerms.carLength,this.queryTerms.inputPerson,
            this.queryTerms.driver,this.queryTerms.driverPhone,this.queryTerms.carrierCategory,this.queryTerms.mainRoute,this.queryTerms.isEnabled,this.queryTerms.startTime,
            this.queryTerms.endTime,0,-1);
        }
    }

}

angular.module("tms").controller("carManagentController", ["$scope", "carService", "valueService", "$ngBootbox", "$state","$timeout" ,"exportService","$location", carManagentController]);